﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;
using System.IO;

namespace WebApplication1
{
    public partial class AddFood : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterScript();
          
            if (!IsPostBack)
            {

                BindFood();
            }
        }
        public void RegisterScript()
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "Action", @" 
                        $(function () {
                            window.prettyPrint && prettyPrint();

                            // disabling dates
                            var nowTemp = new Date();
                            var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);

                            var checkin = $('#dpdStart').datepicker({
                                onRender: function (date) {
                                    return date.valueOf() < now.valueOf() ? 'disabled' : '';
                                }
                            }).on('changeDate', function (ev) {
                                if (ev.date.valueOf() > checkout.date.valueOf()) {
                                    var newDate = new Date(ev.date)
                                    newDate.setDate(newDate.getDate() + 1);
                                    checkout.setValue(newDate);
                                }
                                checkin.hide();
                                $('#dpdEnd')[0].focus();
                            }).data('datepicker');
                            var checkout = $('#dpdEnd').datepicker({
                                onRender: function (date) {
                                    return date.valueOf() < checkin.date.valueOf() ? 'disabled' : '';
                                }
                            }).on('changeDate', function (ev) {
                                checkout.hide();
                            }).data('datepicker');
                        });
                        $(document).ready()
                        {
                            var div = $(""h2:contains('0')"").parent();
                            div.removeClass(""corner"");
                            div.addClass(""Nocorner"")
                            div.find(""h2"").remove();


                        }", true);

        }
        private void BindFood()
        {
            Business.User userobj = (User)Session["User"];
            if (userobj != null)
            {
                Business.Food fo = new Business.Food();
                List<fos_Food> foodList = fo.GetFoodBy(userobj.email);
                Repeater1.DataSource = foodList;
                Repeater1.DataBind();
            }

        }

        protected void btnAddFood_Click(object sender, EventArgs e)
        {

            Business.User userobj = (User)Session["User"];

            Business.Food fo = new Business.Food();
            DateTime start, end;
            decimal output;
            // Check first
            try
            {
                if (!Decimal.TryParse(txtPrice.Text, out output))
                    throw new Exception("Price must be in number!");
                if (!DateTime.TryParse(dpdStart.Text, out start))
                    throw new Exception("Start date must be in dd/mm/yyyy format! StartDate=" + dpdStart.Text);
                if (!DateTime.TryParse(dpdEnd.Text, out end))
                    throw new Exception("End date must be in dd/mm/yyyy format!");
            }
            catch (Exception ex)
            {
                divMessage.Visible = true;
                divMessage.CssClass = "alert alert-danger  alert-dismissible";
                lblMessage.Text = ex.Message;
                return;
            }


            // Update case
            if (btnAddFood.Text == "Update")
            {
                long foodId = (long)ViewState["Food"];
                fos_Food updatedFood = fo.GetFoodById(foodId);
                updatedFood.FoodDescription = description.InnerText;
                updatedFood.FoodName = txtName.Text;


                try
                {


                    updatedFood.FoodPrice = Convert.ToDecimal(txtPrice.Text);
                    updatedFood.StartDate = start;
                    updatedFood.EndDate = end;
                    updatedFood.FoodName = txtName.Text;
                    if (chkPromotion.Checked)
                    {
                        if (!Decimal.TryParse(txtPromotionPrice.Text, out output))
                            throw new Exception("Price must be in number!");
                        updatedFood.PromotionPrice = output;
                        updatedFood.isPromotion = 1;

                    }
                    else
                    {
                        // no promotion
                        updatedFood.PromotionPrice = 0;
                        updatedFood.isPromotion = 0;
                    }
                    updatedFood.FoodDescription = description.InnerText;
                    if ( fileUpload.HasFile )
                    {
                        updatedFood.FoodPicture = fileUpload.FileBytes;

                    }
                    fo.UpdateFood(updatedFood);
                    divMessage.Visible = true;
                    divMessage.CssClass = "alert alert-success  alert-dismissible";
                    lblMessage.Text = "Food updated!";
                    BindFood();
                    return;
                }
                catch (Exception ex)
                {
                    divMessage.Visible = true;
                    divMessage.CssClass = "alert alert-danger  alert-dismissible";
                    lblMessage.Text = ex.Message;
                    return;
                }


            }

            fos_Food myFood = new fos_Food();
            myFood.FoodName = txtName.Text;
            myFood.FoodDescription = description.InnerText;



            myFood.FoodPrice = Convert.ToDecimal(txtPrice.Text);
            myFood.CreatedBy = userobj.email;
            myFood.CreatedDate = DateTime.Now;
            myFood.LastModifiedBy = userobj.email;
            myFood.LastModifiedDate = DateTime.Now;
            myFood.IsDeleted = 0;

            try
            {
                if (!Decimal.TryParse(txtPrice.Text, out output))
                    throw new Exception("Price must be in number!");
                if (!DateTime.TryParse(dpdStart.Text, out start))
                    throw new Exception("Start date must be in dd/mm/yyyy format! StartDate=" + dpdStart.Text);
                if (!DateTime.TryParse(dpdEnd.Text, out end))
                    throw new Exception("End date must be in dd/mm/yyyy format!");

                myFood.FoodPrice = Convert.ToDecimal(txtPrice.Text);
                myFood.StartDate = start;
                myFood.EndDate = end;
                myFood.FoodName = txtName.Text;
                if (chkPromotion.Checked)
                {
                    if (!Decimal.TryParse(txtPromotionPrice.Text, out output))
                        throw new Exception("Price must be in number!");
                    myFood.PromotionPrice = output;
                    myFood.isPromotion = 1;

                }
                else
                {
                    myFood.isPromotion = 0;
                }
                if (fileUpload.PostedFile != null || fileUpload.HasFile || fileUpload.FileBytes.Length == 0)
                {
                    myFood.FoodPicture = fileUpload.FileBytes;

                }
                else
                {
                    throw new Exception("Please upload food image!");
                }
                fo.SaveFood(myFood);
                divMessage.Visible = true;
                divMessage.CssClass = "alert alert-success  alert-dismissible";
                lblMessage.Text = "Food added!";
                BindFood();

            }
            catch (Exception ex)
            {
                divMessage.Visible = true;
                divMessage.CssClass = "alert alert-danger  alert-dismissible";
                lblMessage.Text = ex.Message;

            }


        }

        public string GetImage(object img)
        {
            byte[] image = (byte[])img;

            byte[] newBytes = Common.convertImageSize(image);

            return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Button Btn = sender as Button;


            long id = Convert.ToInt64(Btn.CommandArgument.ToString());
            Business.Food fd = new Business.Food();
            fd.DeleteFood(id);
            BindFood();


        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            btnAddFood.Text = "Update";
            lblImage.Text = "Re-upload image if necessary";
            Button Btn = sender as Button;  
            long id = Convert.ToInt64(Btn.CommandArgument.ToString());
            Business.Food fd = new Business.Food();
            fos_Food food = fd.GetFoodById(id);
            txtName.Text = food.FoodName;
            txtPrice.Text = food.FoodPrice.ToString();
            dpdStart.Text = ((DateTime)food.StartDate).ToShortDateString();
            dpdEnd.Text = ((DateTime)food.EndDate).ToShortDateString();
            chkPromotion.Checked = Convert.ToBoolean(food.isPromotion);
            if (chkPromotion.Checked)
                txtPromotionPrice.Text = food.PromotionPrice.ToString();
            else
                txtPromotionPrice.Text = "";

            description.InnerText = food.FoodDescription;
            ViewState["Food"] = food.Id;

        }

        protected void chkPromotion_CheckedChanged(object sender, EventArgs e)
        {
            if (chkPromotion.Checked)
                txtPromotionPrice.Enabled = true;
            else
                txtPromotionPrice.Enabled = false;
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            txtName.Text = "";
            txtPrice.Text = "";
            description.InnerText = "";
            chkPromotion.Checked = false;
            dpdStart.Text = "";
            dpdEnd.Text = "";
            txtPromotionPrice.Enabled = false;
            btnAddFood.Text = "Add";

        }

        //protected void FileUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
        //{

        //    Session["fileContents_" + e.FileId] = e.GetContents();
        //    Session["fileExtension_" + e.FileId] = e.FileName.Substring(e.FileName.LastIndexOf('.'));
        //    string fileNameWithPath = Server.MapPath("~/UploadedImages/") + e.FileName.ToString();
        //    AjaxFileUpload1.SaveAs(fileNameWithPath);
            
        //}

        //protected void UploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        //{
        //    HttpPostedFile file = AsyncFileUpload1.PostedFile;
        //    byte[] fileData = null;
        //    using (var binaryReader = new BinaryReader(file.InputStream))
        //    {
        //        fileData = binaryReader.ReadBytes(file.ContentLength);
        //    }
        //    Session["File"] = fileData;
        //}      
    }
}